package com.zz.employeedaoimpl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.connector.Request;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestParam;
import com.zz.employeedao.EmployeeDao;
import com.zz.personmodel.Employee;

@Repository
public class EmployeeDaoImpl implements EmployeeDao {
	@Autowired
	private SessionFactory sessionfactory;
    private Map<String,Integer> sizemap;
	// 事物管理但是用不了显示没有Session只能自己open了
	public Session getSession() {
		return sessionfactory.getCurrentSession();
	}
   
	@Override
	public String updateEmployee(@RequestParam(value = "id", required = false) int id,
			@RequestParam(value = "identity_number", required = false) String identity_number,
			@RequestParam(value = "person_name", required = false) String person_name,
			@RequestParam(value = "birth_time", required = false) String birth_time,
			@RequestParam(value = "sex") String sex, @RequestParam(value = "matital_status") String matital_status,
			@RequestParam(value = "spouse_name") String spouse_name) {
		// TODO Auto-generted method stub
		Session session = sessionfactory.openSession();
		Transaction ts = session.getTransaction();
		Date date = new Date();
		Date date1 = new Date();
		String updateVerify = "";// 校验字符串
		SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
		try {
			birth_time = birth_time.replace(",", "");// 添加进来有，号除掉，号
			date = sdf.parse(birth_time);
			birth_time = birth_time.replace("-", "");
			ts.begin();
			// 验证5项是否为空其余两项下拉有默认值
			if (identity_number != "" && person_name != "" && matital_status != "") {
				// 采用load查询不存在的数据,hibernate会抛出object not found exception
				Query query2 = session.createQuery("from Employee as e where e.identity_number=:identity_number");
				query2.setString("identity_number", identity_number);
				List<Employee> list =query2.list();
				Query query = session.createQuery("from Employee as e where e.identity_number=:identity_number and e.id=:id");
				query.setString("identity_number", identity_number);
				query.setParameter("id", id);
				List<Employee> l =query.list();
				// 判断身份证是否存在
				if (list.isEmpty()||!l.isEmpty()) {
					// 判断身份证是否与生日!匹配是开始修改并返回成功信息否返回校验信息
					if (identity_number.contains(birth_time)) {
						Employee e = (Employee) session.load(Employee.class, id);// 获取id
						e.setIdentity_number(identity_number);// 更改数据
						e.setPerson_name(person_name);
						e.setBirth_time(date);
						e.setGender(sex);
						e.setLaste_update_time(date1);
						e.setMatital_status(matital_status);
						e.setSpouse_name(spouse_name);
						session.update(e);
						ts.commit();
						updateVerify = "修改成功";
					} else {
						updateVerify = "身份证必须和生日匹配！";
					}
				}else {
					updateVerify = "身份證已存在！";
				}
			} else {
				updateVerify = "姓名，身份证号码，性别，出生年份，婚姻状况必填！谢谢合作!";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		session.close();
		return updateVerify;
	}
	// 查看数据库数据
	public int getperson(@RequestParam(value = "person_name", required = false) String person_name,
			@RequestParam(value = "birth_time", required = false) String birth_time,
			@RequestParam(value = "gender", required = false) String gender) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		Session session = sessionfactory.openSession();// 打开Session
		Query query = null;
		if (birth_time == "") {
			query = session.createQuery("from Employee as e where e.person_name=:person_name and e.gender=:gender");
			query.setString("person_name", person_name);
			query.setString("gender", gender);
		}
		if (gender == "") {
			query = session.createQuery(
					"from Employee as e where e.person_name=:person_name and to_char(birth_time ,'yyyy')like:birth_time");
			query.setString("person_name", person_name);
			query.setString("birth_time", birth_time);
		}
		if (person_name == "") {
			query = session.createQuery(
					"select e from Employee as e where e.gender=:gender and to_char(birth_time ,'yyyy')like:birth_time");
			query.setString("gender", gender);
			query.setString("birth_time", birth_time);
		}
	  List<Employee> findlist = query.list();// 得到所有的结果集
	   int size =findlist.size();
	   session.close();
	   System.out.println(size+person_name+gender);
	   return size;
	}
	// 查找员工
	@Override
	public List<Employee> findEmployee(
			@RequestParam(value = "identity_number", required = false) String identity_number,
			@RequestParam(value = "person_name", required = false) String person_name,
			@RequestParam(value = "birth_time", required = false) String birth_time,
			@RequestParam(value = "gender", required = false) String gender,
			@RequestParam(value = "page", required = false) Integer page) {
		// TODO Auto-generated method stub,
		//@RequestParam查询传值为""分页传值为null要把两者统一
		if(identity_number==null) {
			identity_number="";
		}
		if(gender==null) {
			gender="";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		Session session = sessionfactory.openSession();// 打开Session
		Query query = null;
		if (identity_number!= "") {
			query = session.createQuery("from Employee as e where e.identity_number=:identity_number");
			query.setString("identity_number", identity_number);
			query.setFirstResult(0);
			query.setMaxResults(4);
		} else {
			if (birth_time == "") {
				query = session.createQuery("from Employee as e where e.person_name=:person_name and e.gender=:gender");
				query.setString("person_name", person_name);
				query.setString("gender", gender);
				query.setFirstResult(page);
				query.setMaxResults(4);
			}
			if (gender == "") {
				query = session.createQuery(
						"from Employee as e where e.person_name=:person_name and to_char(birth_time ,'yyyy')like:birth_time");
				query.setString("person_name", person_name);
				query.setString("birth_time", birth_time);
				query.setFirstResult(page);
				query.setMaxResults(4);
			}
			if (person_name == "") {
				query = session.createQuery(
						"select e from Employee as e where e.gender=:gender and to_char(birth_time ,'yyyy')like:birth_time");
				query.setString("gender", gender);
				query.setString("birth_time", birth_time);
				query.setFirstResult(page);
				query.setMaxResults(4);
			}
		}
		List<Employee> findlist = query.list();// 得到所有的结果集
		System.out.println("identity_number：" + identity_number + "person_name：" + person_name + "birth_time："
				+ birth_time + "gender：" + gender+ "page"+page);// 检查数据是否传入
		session.close();
		return findlist;
	}

	@Override
	public String viewEmployee(Employee employee, String ID) {
		// TODO Auto-generated method stub
		return null;
	}

	// 添加数据
	@Override
	public String addEmployee(@RequestParam(value = "identity_number", required = false) String identity_number,
			@RequestParam(value = "person_name", required = false) String person_name,
			@RequestParam(value = "birth_time", required = false) String birth_time,
			@RequestParam(value = "sex") String sex, @RequestParam(value = "matital_status") String matital_status,
			@RequestParam(value = "spouse_name") String spouse_name) {
		// TODO Auto-generated method stub
		// String hql = "UPDATE Employee SET person_name = employee. WHERE id = ?";
		// Query query= getSession().createQuery(hql);
		// query.setParameter(0, person_name);
		// query.setParameter(1, id);
		// query.executeUpdate();
		String addVerify = "";// 定义校验字符串
		Date date = new Date();// 获取当前时间
		Date date1;// 传入的生日转换到date1
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			birth_time = birth_time.replace(",", "");// 添加进来有，号除掉，号
			System.out.println(birth_time);
			date1 = (Date) sdf.parse(birth_time);// 转换为date类型
			System.out.println(date1);
			birth_time = birth_time.replace("-", "");// 替换掉-方便与身份证比较
			Employee ee = new Employee();
			Session s = sessionfactory.openSession();
			Transaction ts = s.getTransaction();
			// Date d=new Date(birth_time);
			try {
				// 开启事务
				ts.begin();
				// 先验证五项是否为空
				if (identity_number != "" && person_name != "" && matital_status != "") {
					// 在验证身份证是否存在
					Query query = s.createQuery("select identity_number from Employee");
					List<String> l = query.list();
					if (l.contains(identity_number)) {
						addVerify = "该身份证已经存在！";
					} else {
						// 最后验证身份证是否和生日相同
						if (identity_number.contains(birth_time)) {
							ee.setPerson_name(person_name);
							ee.setCreate_time(date);
							ee.setLaste_update_time(date);
							ee.setVersion_number(111);
							ee.setGender(sex);
							ee.setBirth_time(date1);
							ee.setIdentity_number(identity_number);
							ee.setMatital_status(matital_status);
							ee.setSpouse_name(spouse_name);
							s.save(ee);
							ts.commit();
							addVerify = "添加成功!";
						} else {
							addVerify = "出生日期要和身份证匹配!";
						}
					}
				} else {
					addVerify = "姓名，身份证号码，性别，出生年份，婚姻状况必填！谢谢合作";
				}
			} catch (Exception e) {
				e.printStackTrace();
				// 事务回滚
				ts.rollback();
			}
			s.close();
		} catch (

		ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return addVerify;
	}

	// 删除
	@Override
	public boolean deletEmployee(@RequestParam(value = "id", required = false) int id) {
		// TODO Auto-generated method stub
		boolean b = false;// 判断是否删除成功
		Session session = sessionfactory.openSession();
		Transaction ts = session.getTransaction();
		try {
			// 开启事物
			ts.begin();
			// 采用load查询不存在的数据,hibernate会抛出object not found exception
			Employee employee = (Employee) session.load(Employee.class, id);
			// 删除表中的记录.
			// 删除,用此种方式删除,先加载再删除.用get就是没有加载上去就是干
			//
			session.delete(employee);
			// 提交事物并把内存改变提交到数据库
			b = true;
			ts.commit();
		} catch (Exception e) {
			e.printStackTrace();
			ts.rollback();
		}
		System.out.println(id);
		session.close();
		return b;
	}

}
